<?php

namespace Iwester\Http\Model\Article;

use Iwester\Http\Model\Base;
use Illuminate\Support\Facades\Cache;

class ArticleTag extends Base
{
    protected $table = 'article_tags';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'tag', 'status', 'user_id',
    ];

    //与文章多对多关联
    public function articles()
    {
        return $this->belongsToMany('Iwester\Http\Model\Article\Article', 'article_tag_pivot', 'article_tag_id', 'article_id');
    }

    /**
     * getTags
     * @return mixed
     */
    public static function getTags($showAll = false)
    {
        $tags = ArticleTag::with('articleCount')->select(['*']);
        if (!$showAll) {
            $tags->where('status', 1);
        }
        return $tags->get();
    }

    /**
     * 判断标签是否已存在
     * @param $tag
     * @return bool
     */
    public static function checkTag($tag, $id=0)
    {
        $query = ArticleTag::where('tag', $tag);
        if ($id) $query->where('id', '<>', $id);
        return $query->exists();
    }

    /**
     * 获取当前标签文章数量
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function articleCount()
    {
        return $this->hasMany(ArticleTagPivot::class, 'article_tag_id', 'id');
    }

    /**
     * 获取当前标签文章
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public static function articleReal($tag)
    {
        return ArticleTagPivot::leftJoin('articles', 'articles.id', '=', 'article_tag_pivot.article_id')
            ->where(['articles.publish_status'=> 1, 'articles.audit_status'=> 1, 'article_tag_pivot.article_tag_id'=> $tag->id]);
    }
}